﻿@page "/"
@using Microsoft.Identity.Client
@using CommunityToolkit.Maui.Alerts
@using System.Text
@using AuthServices
@inject AuthService authService
@inject AuthServiceB2C authServiceB2C

<button @onclick="LoginAsync">Login</button>
<button @onclick="LoginB2CAsync">Login B2C</button>
<p>@resultMessage</p>
@code
{
	string resultMessage = string.Empty;

	async Task LoginAsync()
	{
		try
		{
			var result = await authService.SignInInteractively(CancellationToken.None);
			GetResult(result);
		}
		catch (MsalClientException ex)
		{
			await Toast.Make(ex.Message).Show();
		}
	}
	async Task LoginB2CAsync()
	{
		try
		{
			var result = await authServiceB2C.SignInInteractively(CancellationToken.None);
			GetResult(result);
		}
		catch (MsalClientException ex)
		{
			await Toast.Make(ex.Message).Show();
		}
	}

	void GetResult(AuthenticationResult? result)
	{
		var claims = result?.ClaimsPrincipal.Claims;
		if (claims != null)
		{
			var stringBuilder = new StringBuilder();
			stringBuilder.AppendLine($"Name: {claims.FirstOrDefault(x => x.Type.Equals("name"))?.Value}");
			resultMessage = stringBuilder.ToString();
		}
	}
}
